<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item
        label="门店名称"
        prop="shopName"
        v-hasPermi="['business:hairTeacherSubscribe:queryShopName']"
      >
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="所属军区"
        prop="theirMilitary"
        v-hasPermi="['business:hairTeacherSubscribe:queryTheirMilitary']"
      >
        <el-select
          v-model="queryParams.theirMilitary"
          placeholder="请选择所属军区"
        >
          <el-option
            v-for="dict in belong_military_region"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
            @change="handleQuery"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期" prop="subscribeDate">
        <el-date-picker
          clearable
          v-model="queryParams.subscribeDate"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择预约日期"
          style="width: 150px"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <!-- <el-button icon="Refresh" @click="resetQuery">重置</el-button> -->
      </el-form-item>
    </el-form>
    <el-table
      v-loading="loading"
      :data="hairFixShopList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column label="所属军区" align="center" prop="theirMilitary" />
      <el-table-column
        label="门店名称"
        width="200"
        align="center"
        prop="shopName"
      />
      <el-table-column
        width="200"
        label="老师名称"
        align="center"
        prop="teacherName"
      />

      <!-- <el-table-column
        :label="item.key"
        align="center"
        prop="item.key"
        v-for="item in timeList"
      >
        <template #default="scope">
          <template v-if="scope.row.dateValue.key == item.key">
            <div>
              <div>
                {{ scope.row.dateValue.userName }}
              </div>
              <div>
                {{ scope.row.dateValue.subscribeType }}
              </div>
              <div>
                <el-tag v-if="scope.row.dateValue.status === 0">待到店</el-tag>
                <el-tag
                  v-else-if="scope.row.dateValue.status === 1"
                  class="ml-2"
                  type="success"
                  >已完成</el-tag
                >
                <el-tag v-else class="ml-2" type="info">已取消</el-tag>
              </div>
            </div>
          </template>
        </template>
      </el-table-column> -->

      <!-- item.key == el.key -->
      <template v-for="(item, index) in timeList">
        <el-table-column :label="item.key" align="center" prop="item.key">
          <template #default="scope">
            <template v-for="(el, k) in scope.row.dateValue">
              <div></div>
              <div
                v-if="
                  el.bookedTime >= item.startTime &&
                  el.bookedTime < item.endTime
                "
              >
                <div
                  v-for="(v, k) in el.timeValue"
                  class="info-content"
                  style="
                    border: 1px solid #e2e2e2;
                    margin-top: 8px;
                    padding-bottom: 5px;
                  "
                >
                  <div>{{ v.key }}</div>
                  <div>
                    {{ v.userName }}
                  </div>
                  <div>
                    {{ v.subscribeType }}
                  </div>
                  <div>
                    <el-tag v-if="v.status === 0">待到店</el-tag>
                    <el-tag
                      v-else-if="v.status === 1"
                      class="ml-2"
                      type="success"
                      >已完成</el-tag
                    >
                    <el-tag v-else class="ml-2" type="info">已取消</el-tag>
                  </div>

                  <!-- {{ v.userName }} -->
                </div>
              </div>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改补发师门店对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form
        ref="hairFixShopRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="门店名称" prop="shopName">
          <el-input
            v-model="form.shopName"
            placeholder="请输入门店名称"
            style="width: 215px"
          />
        </el-form-item>
        <el-form-item label="所属军区" prop="theirMilitary">
          <el-select v-model="form.theirMilitary" placeholder="请选择所属军区">
            <el-option
              v-for="dict in belong_military_region"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              @change="handleQuery"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="店铺类型" prop="shopType">
          <el-select v-model="form.shopType" placeholder="请选择店铺类型">
            <el-option
              v-for="dict in shop_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
              @change="handleQuery"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="地区选择" prop="regionValue">
          <el-cascader
            v-model="regionValue"
            :options="sysCityListAll"
            :props="{
              children: 'children',
              label: 'label',
              value: 'label',
            }"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="具体地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入具体地址" />
        </el-form-item>

        <el-form-item label="手动定位" prop="location">
          <el-button open-type="" hover-class="button-hover" @click="openMap">
            点击打开地图
          </el-button>
        </el-form-item>
        <!-- <el-form-item label="经度" prop="lon">
          <el-input v-model="form.lon" placeholder="请输入经度" />
        </el-form-item> -->
        <!-- <el-form-item label="纬度" prop="lat">
          <el-input v-model="form.lat" placeholder="请输入纬度" />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 显示地图搜索和定位 -->
    <div class="locations-map" v-if="isMapFlag">
      <locations
        :locationName="form.address"
        @mapClick="handleMapClick"
      ></locations>
    </div>
  </div>
</template>

<script setup name="HairFixShop">
import {
  listHairFixShopBooked,
  getHairFixShop,
  delHairFixShop,
  addHairFixShop,
  updateHairFixShop,
  getProvince,
} from "@/api/business/hairFixShop";
import { listSystemCityAll } from "@/api/business/systemCity";
import ImageUploads from "@/components/ImageUploads/index.vue";
import locations from "@/components/locations/index.vue";

const { proxy } = getCurrentInstance();
const { shop_type, belong_military_region } = proxy.useDict(
  "shop_type",
  "belong_military_region"
);

// 地区数据
const regionValue = ref([]);
const hairFixShopList = ref([]);
const sysCityListAll = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const isMapFlag = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    shopType: undefined,
    shopName: undefined,
    shopCarousel: undefined,
    province: undefined,
    city: undefined,
    area: undefined,
    address: undefined,
    lon: undefined,
    lat: undefined,
    point: undefined,
    theirMilitary: undefined,
    subscribeDate: proxy.parseTime(new Date(), "{y}-{m}-{d}"),
  },
  rules: {
    id: [{ required: true, message: "不能为空", trigger: "blur" }],
    shopName: [
      { required: true, message: "门店名称不能为空", trigger: "blur" },
    ],
    theirMilitary: [
      { required: true, message: "所属军区不能为空", trigger: "blur" },
    ],
    shopType: [
      { required: true, message: "店铺类型不能为空", trigger: "blur" },
    ],
    province: [{ required: true, message: "省不能为空", trigger: "blur" }],
    city: [{ required: true, message: "市不能为空", trigger: "blur" }],
    area: [{ required: true, message: "区不能为空", trigger: "blur" }],
    address: [{ required: true, message: "具体地址不能为空", trigger: "blur" }],
    lon: [{ required: true, message: "经度不能为空", trigger: "blur" }],
    lat: [{ required: true, message: "纬度不能为空", trigger: "blur" }],
    point: [{ required: true, message: "经纬度不能为空", trigger: "blur" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

const timeList = ref([]);

console.log(timeList.value);

// 选择省
const provinceList = ref([]);
const chooseprovince = async () => {
  provinceList.value = await getProvince();
  console.log("选择省", provinceList.value);
};

// 从子组件获取经纬度
const handleMapClick = (e) => {
  if (e.lat || e.lng) {
    form.value.lon = e.lng;
    form.value.lat = e.lat;
  }
  isMapFlag.value = e.isMapFlag;
};

// 是否显示地图搜索和定位
const openMap = () => {
  // return;
  isMapFlag.value = true;
};

/** 查询补发师门店列表 */
function getList() {
  loading.value = true;
  listHairFixShopBooked(queryParams.value).then((response) => {
    // response.rows.forEach((el) => {
    //   console.log(el.dateValue);
    //   timeList.value.map((item) => {
    //     if (item.key == el.dateValue.key) {
    //       el.bookedDateValue = el.dateValue;
    //     }
    //   });
    // });
    response.data.list.forEach((item) => {
      item.dateValue.forEach((el) => {
        el.bookedTime = new Date(
          `${queryParams.value.subscribeDate} ${el.key}`
        ).getTime();
      });
    });

    hairFixShopList.value = response.data.list;
    total.value = response.data.total;
    loading.value = false;
    console.log("门店预约列表", response);
  });
}

function getCityListAll() {
  listSystemCityAll().then((res) => {
    sysCityListAll.value = res.data;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    shopName: null,
    shopCarousel: null,
    theirMilitary: null,
    province: null,
    city: null,
    area: null,
    shopType: null,
    address: null,
    lon: null,
    lat: null,
    point: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null,
  };
  regionValue.value = [];
  proxy.resetForm("hairFixShopRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
  onTimeList(queryParams.value);
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.subscribeDate = null;
  queryParams.value.theirMilitary = null;
  queryParams.value.shopName = null;
  handleQuery();

  onTimeList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加补发师门店";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true;
  reset();
  const _id = row.id || ids.value;
  getHairFixShop(_id).then((response) => {
    loading.value = false;
    form.value = response.data;
    regionValue.value.push(response.data.province);
    regionValue.value.push(response.data.city);
    regionValue.value.push(response.data.area);
    open.value = true;
    title.value = "修改补发师门店";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["hairFixShopRef"].validate((valid) => {
    console.log(form.value);
    // return;
    if (regionValue.length !== 0) {
      form.value.province = regionValue.value[0];
      form.value.city = regionValue.value[1];
      form.value.area = regionValue.value[2];
    }
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id != null) {
        updateHairFixShop(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
            regionValue.value = [];
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        addHairFixShop(form.value)
          .then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
            regionValue.value = [];
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除补发师门店编号为"' + _ids + '"的数据项？')
    .then(function () {
      loading.value = true;
      return delHairFixShop(_ids);
    })
    .then(() => {
      loading.value = true;
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {})
    .finally(() => {
      loading.value = false;
    });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "business/hairFixShop/export",
    {
      ...queryParams.value,
    },
    `hairFixShop_${new Date().getTime()}.xlsx`
  );
}
onTimeList(queryParams.value);
getCityListAll();
getList();

function onTimeList(time) {
  console.log(time);
  if (!time || time == undefined) {
    time = {
      subscribeDate: "2023-01-01",
    };
  }
  timeList.value = [
    {
      id: 1,
      key: "9:00",
      startTime: new Date(`${time.subscribeDate} 09:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 09:00:00`).getTime() + Number(3600000),
    },
    {
      id: 2,
      key: "10:00",
      startTime: new Date(`${time.subscribeDate} 10:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 10:00:00`).getTime() + Number(3600000),
    },
    {
      id: 3,
      key: "11:00",
      startTime: new Date(`${time.subscribeDate} 11:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 11:00:00`).getTime() + Number(3600000),
    },
    {
      id: 4,
      key: "12:00",
      startTime: new Date(`${time.subscribeDate} 12:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 12:00:00`).getTime() + Number(3600000),
    },
    {
      id: 5,
      key: "13:00",
      startTime: new Date(`${time.subscribeDate} 13:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 13:00:00`).getTime() + Number(3600000),
    },
    {
      id: 6,
      key: "14:00",
      startTime: new Date(`${time.subscribeDate} 14:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 14:00:00`).getTime() + Number(3600000),
    },
    {
      id: 7,
      key: "15:00",
      startTime: new Date(`${time.subscribeDate} 15:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 15:00:00`).getTime() + Number(3600000),
    },
    {
      id: 8,
      key: "16:00",
      startTime: new Date(`${time.subscribeDate} 16:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 16:00:00`).getTime() + Number(3600000),
    },
    {
      id: 9,
      key: "17:00",
      startTime: new Date(`${time.subscribeDate} 17:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 17:00:00`).getTime() + Number(3600000),
    },
    {
      id: 10,
      key: "18:00",
      startTime: new Date(`${time.subscribeDate} 18:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 18:00:00`).getTime() + Number(3600000),
    },
    {
      id: 11,
      key: "19:00",
      startTime: new Date(`${time.subscribeDate} 19:00:0`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 19:00:00`).getTime() + Number(3600000),
    },
    {
      id: 11,
      key: "20:00",
      startTime: new Date(`${time.subscribeDate} 20:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 20:00:00`).getTime() + Number(3600000),
    },
    {
      id: 11,
      key: "21:00",
      startTime: new Date(`${time.subscribeDate} 21:00:00`).getTime(),
      endTime:
        new Date(`${time.subscribeDate} 21:00:00`).getTime() + Number(3600000),
    },
  ];
  console.log("======", timeList.value);
}
</script>
<style>
.info-content {
  border: 2rpx solid #000000;
  padding: 10rpx;
}
</style>
